<!DOCTYPE html>
<html>

<head>
    <title>管理章模版</title>
    <link rel="icon" href="/logo.png" type="image/x-icon" />
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Cache-Control" content="only-if-cached">
    <style>
        pre {
            white-space: pre-wrap;
            /* CSS-3 /
           white-space: -moz-pre-wrap; / Mozilla, since 1999 /
           white-space: -pre-wrap; / Opera 4-6 /
           white-space: -o-pre-wrap; / Opera 7 /
           Word-wrap: break-word; / Internet Explorer 5.5+ */
        }

        .textarea {
            width: 100%;
            min-height: 30px;
            max-height: 700px;
            outline: 0;
            border: 1px solid #000;
            font-size: 16px;
            overflow-x: hidden;
            overflow-y: auto;
            -webkit-user-modify: read-write-plaintext-only;
        }

        [contentEditable=true]:empty:not(:focus):before {
            content: attr(data-text);
        }
    </style>

    <script type="text/javascript" src="vue2.7.js"></script>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="config.js"></script>

</head>

<body>
    <div id="app">

        <div class="bg-light text-black text-center" style="padding: 6px;">
            <h4 style="align-content: center">管理章模版</h4>

            <div style="display: flex; padding-top: 55px;text-align: left">

                <div style="width: 50%">
                    <div class="bg-light" style="border-radius:25px;padding: 1.5%">
                        <div v-if="models.length > 0">

                            <ul v-if="maxPage>1" class="pagination justify-content-center" style="margin-bottom:10px">
                                <li v-if="curPage>1" class="page-item" @click="fetchData(1)"><a class="page-link"
                                        href="#">首页</a></li>
                                <li v-if="curPage>1" class="page-item" @click="fetchData(curPage-1)">
                                    <a class="page-link" href="#"><span>&laquo;</span></a>
                                </li>

                                <li v-if="curPage>2" class="page-item" @click="fetchData(curPage-2)"><a
                                        class="page-link" href="#">{{curPage-2}}</a>
                                </li>
                                <li v-if="curPage>1" class="page-item" @click="fetchData(curPage-1)"><a
                                        class="page-link" href="#">{{curPage-1}}</a>
                                </li>

                                <li class="page-item active"><a class="page-link" href="#">{{curPage}}</a></li>

                                <li v-if="curPage<maxPage" class="page-item" @click="fetchData(curPage+1)"><a
                                        class="page-link" href="#">{{curPage+1}}</a></li>
                                <li v-if="curPage<(maxPage-1)" class="page-item" @click="fetchData(curPage+2)"><a
                                        class="page-link" href="#">{{curPage+2}}</a></li>

                                <li v-if="curPage<maxPage" class="page-item" @click="fetchData(curPage+1)">
                                    <a class="page-link" href="#"><span>&raquo;</span></a>
                                </li>
                                <li v-if="curPage<maxPage" class="page-item" @click="fetchData(maxPage)">
                                    <a class="page-link" href="#">尾页</a>
                                </li>
                            </ul>

                            <ul class="list-group" style="list-style: none;margin-top:0;padding:0%;">
                                <li v-for="obj in models" style="margin-top: 1.5%;margin-bottom: 1.5%;padding:0">
                                    <div class="card" style="border-radius:25px;padding: 16px;background: white">
                                        <div style="display: flex;flex-direction: row" v-if="obj">
                                            <div style="display: flex;flex-direction: column;width: 84%">
                                                <span
                                                    style="font-size: 22px;color:black;font-weight: 400;line-height: 23px;">
                                                    {{ obj.title }}
                                                </span>

                                                <div style="display: flex;">
                                                    <span
                                                        style="font-size: 16px;color:orange;font-weight: 300;margin-top: 4px;">
                                                        {{ formatType(obj.subjectType) }}
                                                    </span>

                                                    <span v-if="obj.pass"
                                                        style="border: 1px solid #17af66;padding: 0px 5px;font-size: 12px;border-radius: 5px;margin-left: 10px;color: #17af66;height: 20px;margin-top: 6px;">已通过</span>
                                                    <span v-else-if="!!(obj.audit)"
                                                        style="border: 1px solid #f00;padding: 0px 5px;font-size: 12px;border-radius: 5px;margin-left: 10px;color: #f00;height: 20px;margin-top: 6px;">不通过</span>
                                                    <span v-else
                                                        style="border: 1px solid #ffaa00;padding: 0px 5px;font-size: 12px;border-radius: 5px;margin-left: 10px;color: #ffaa00;height: 20px;margin-top: 6px;">未审核</span>
                                                </div>

                                                <span v-if="obj.audit"
                                                    style="border: 1px solid #f00;padding: 0px 5px;font-size: 12px;border-radius: 5px;color: #f00;height: 20px;margin-top: 5px;">{{'评审意见:'
                                                    + obj.audit}}</span>

                                                <div style="display: flex;">
                                                    <span style="font-size: 16px;color:#555;font-weight: 300;">
                                                        {{ obj.author +" " + formatDate(obj.timeMills) }}
                                                    </span>
                                                </div>

                                                <span style="background-color: #eee;margin-top: 5px">
                                                    {{ obj.content.substring(0,38) }}
                                                </span>
                                            </div>
                                            <button type="button" class="btn btn-block btn-warning"
                                                @click="configModel(obj)"
                                                style="width: 11%;border-radius:15px;margin-left:2%;margin-top:15px;margin-bottom:15px;">
                                                查看
                                            </button>
                                            <button v-if="tokenObj.admin || !obj.pass" type="button"
                                                class="btn btn-block btn-danger" @click="delModel(obj)"
                                                style="width: 11%;border-radius:15px;margin-left:2%;margin-top:15px;margin-bottom:15px;">
                                                删除
                                            </button>
                                        </div>

                                    </div>

                                </li>
                            </ul>
                        </div>
                        <p v-else>
                            无可用数据
                        </p>
                    </div>
                </div>

                <div style="width: 50%">
                    <div class="card border-info bg-light"
                        style="border-radius:25px;padding: 3% 3% 3% 3%;max-width: 900px">

                        <button type="button" style="margin: 10px;width: 35%;" @click="resetEdit">
                            重置编辑区
                        </button>

                        <span
                            style="font-size: 22px;color:black;font-weight: 400;line-height: 23px;margin: 10px 0">{{hintTitle}}</span>

                        <div id="form">
                            <label>章标题:</label>
                            <div id="inputName" class="textarea" contenteditable="true" data-text="输入标题"></div>
                            <br>
                            <label>适用行业:</label>

                            <div style="display: flex;">
                                <input id="checkbox1" type="checkbox" name="group" value="8" v-model="checkedData"
                                    @change="handleChange($event)">
                                <label for="checkbox1">建筑</label>

                                <input id="checkbox2" type="checkbox" name="group" value="4" v-model="checkedData"
                                    @change="handleChange($event)" style="margin-left: 10px;">
                                <label for="checkbox2">市政</label>

                                <input id="checkbox3" type="checkbox" name="group" value="2" v-model="checkedData"
                                    @change="handleChange($event)" style="margin-left: 10px;">
                                <label for="checkbox3">水利</label>

                                <input id="checkbox4" type="checkbox" name="group" value="1" v-model="checkedData"
                                    @change="handleChange($event)" style="margin-left: 10px;">
                                <label for="checkbox4">公路</label>
                            </div>

                            <label style="margin-top: 15px;">内容模版:</label>
                            <div id="input1" class="textarea" contenteditable="true" data-text="输入模版内容"></div>
                        </div>

                        <button v-if="configObj===null || !configObj.pass" type="button"
                            class="btn btn-block btn-success" style="margin-top: 20px;" @click="commit" id="btnSubmit">
                            提交
                        </button>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script>
        var tokenInfo = localStorage.getItem('tokenInfo')
        var tokenObj = JSON.parse(tokenInfo)

        function sum(arr) {
            return arr.reduce(function (a, b) {
                return parseInt(a) + parseInt(b);
            }, 0);
        }

        function formatDate(milliseconds) {
            // console.log('formatDate type:', typeof (milliseconds))
            // console.log('formatDate:', parseInt(milliseconds))
            if (!milliseconds) {
                return '';
            }
            var date = new Date(parseInt(milliseconds));
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        }

        function formatType(type) {
            // console.log('formatType', type);
            let ret = '';
            // 建筑 市政 水利 公路
            let shiftNum = type >> 3;
            if (shiftNum & 1) {
                ret += '建筑 ';
            }
            shiftNum = type >> 2;
            if (shiftNum & 1) {
                ret += '市政 ';
            }
            shiftNum = type >> 1;
            if (shiftNum & 1) {
                ret += '水利 ';
            }
            shiftNum = type >> 0;
            if (shiftNum & 1) {
                ret += '公路';
            }
            return ret;
        }

        var app = new Vue({
            el: "#app",
            data: {
                // models: Vue.observable([]),
                models: Vue.observable([]),
                retLi: [],
                selected: -1,
                curPage: 0,
                maxPage: 0,
                checkedData: [8],
                hintTitle: "新建章模版",
                configObj: null
            },
            methods: {

                configModel: function (obj) {
                    app.configObj = obj;
                    resetInput();
                    document.getElementById("inputName").innerHTML = obj.title;
                    document.getElementById("input1").innerHTML = obj.content;
                    let type = obj.subjectType;
                    // console.log('type', typeof type);
                    app.checkedData = [];
                    for (let i = 0; i < 4; i++) {
                        const shiftedNum = type >> i;
                        let lastBit = (shiftedNum & 1) << i;
                        app.checkedData.push(lastBit);
                    }
                },
                delModel: function (obj) {
                    app.models = app.models.filter(e => e._id !== obj._id)
                    delDoc1(obj._id)
                },
                handleChange: function (event) {
                    // const isChecked = event.target.checked;
                    // const value = event.target.value;
                    // console.log('sum:', sum(app.checkedData));
                }
            },
        })

        function refreshCache() {
            var sortFunc = function (a, b) {
                if (typeof a.contentCode !== 'string' || typeof b.contentCode !== 'string') {
                    return 1;
                }
                var fieldA = a.contentCode.toLowerCase(); // 将字段转换为小写以进行不区分大小写的排序
                var fieldB = b.contentCode.toLowerCase(); // 将字段转换为小写以进行不区分大小写的排序

                // 使用 localeCompare 进行字符串的比较
                if (fieldA < fieldB) {
                    return -1;
                }
                if (fieldA > fieldB) {
                    return 1;
                }
                return 0; // 相等的情况
            };
            // app.models = app.models.sort(sortFunc);
            let modelsTspStr = localStorage.getItem('modelsTsp')
            let modelsTsp = parseFloat(modelsTspStr)
            if ((Date.now() - modelsTsp) < 24 * 60 * 60 * 1000) {
                console.log('fetchModels use cache')
                let modelsStr = localStorage.getItem('models')
                let models = JSON.parse(modelsStr)
                app.models = models
                if (models?.length > 0) {
                    return;
                }
            }
            fetchData()
        }

        function fetchData(page) {
            if (tokenInfo) {
                var params = JSON.parse(tokenInfo)
                let url = new URL(baseUrl + '/doc1');
                url.searchParams.append('username', params.username);
                url.searchParams.append('token', params.token);
                if (page) {
                    url.searchParams.append('page', page);
                }
                fetch(url.toString())
                    .then(response => response.json())
                    .then(res => {
                        if (res.code === 200) {
                            app.models = res.res;
                            app.curPage = parseInt(res.curPage);
                            app.maxPage = parseInt(res.maxPage);
                            console.log("fetchModels size: " + res.res.length)
                            console.log("curPage: " + res.curPage)
                            console.log("maxPage: " + res.maxPage)
                            // app.models = app.models.sort(sortFunc);
                            localStorage.setItem('models', JSON.stringify(app.models))
                        } else {
                            console.log("fetchM‰odels err: " + res.code)
                        }
                    })
                    .catch(error => console.error(error));
            } else {
                localStorage.setItem('tokenInfo', '')
                alert("登陆过期，请登陆后再试")
                window.open('./login.html')
            }
        }

        // localStorage.removeItem('models')
        refreshCache()

        function resetEdit() {
            app.configObj = null;
            app.checkedData = [8];
            resetInput();
        }

        function resetInput() {
            document.getElementById("inputName").innerHTML = "";
            document.getElementById("input1").innerHTML = "";
            // document.getElementById("contentCode").innerHTML = "";
            app.hintTitle = app.configObj ? "编辑章模版" : "新建章模版";
        }

        function commit() {
            var inList = false
            let inputName = document.getElementById("inputName").innerHTML.trim()
            let subjectType = sum(app.checkedData)
            let content = document.getElementById("input1").innerHTML.trim()
            content = content.replaceAll("&lt;", "<")
            content = content.replaceAll("&gt;", ">")
            if (inputName == null || inputName.length === 0) {
                alert("请输入章名称")
                return
            }
            if (subjectType < 1) {
                alert("请勾选适用行业")
                return
            }

            let isEdit = !!app.configObj;
            let obj = {
                title: inputName,
                subjectType,
                content,
                ...(app.configObj && { _id: app.configObj._id })
            }
            if (isEdit) {
                obj.timeMills = app.configObj.timeMills;
                obj.author = app.configObj.author;
            }
            // save on server
            console.log("commit data...")
            var tokenInfo = localStorage.getItem('tokenInfo')
            if (tokenInfo) {
                let params = JSON.parse(tokenInfo)
                const doc = {
                    ...obj,
                    username: params.username,
                    token: params.token
                }
                const queryString = JSON.stringify(doc)
                const xhr = new XMLHttpRequest()
                xhr.open('POST', '/commitDoc1')
                xhr.setRequestHeader('Content-Type', 'application/json')
                xhr.onload = async function () {
                    let res = JSON.parse(xhr.response);
                    console.log(res)
                    if (res.code === 200) {
                        if (isEdit) {
                            app.configObj = res.ret;
                        }
                        app.models = app.models.filter(e => e._id !== res.ret._id);
                        app.models.unshift(res.ret);
                        resetEdit();
                        alert(res.msg);
                    } else if (res.code === 407) {
                        alert(res.msg);
                    } else {
                        localStorage.setItem('tokenInfo', '')
                        alert("登陆过期，请登陆后再试")
                        window.open('./login.html')
                    }
                }
                xhr.send(queryString)
            } else {
                localStorage.setItem('tokenInfo', '')
                alert("登陆过期，请登陆后再试")
                window.open('./login.html')
            }
        }

        function delDoc1(id) {
            if (tokenInfo) {
                let params = JSON.parse(tokenInfo)
                let obj = {
                    ...params,
                    _id: id,
                }
                let url = new URL(baseUrl + '/delDoc1');
                url.searchParams.append('username', params.username);
                url.searchParams.append('token', params.token);
                url.searchParams.append('_id', id);

                const request = new Request(url.toString(), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(obj),
                });

                fetch(request)
                    .then(response => response.json())
                    .then(res => {
                        if (res.code === 200) {
                            console.log("delDoc1: " + res._id)
                            alert("删除成功")
                        } else {
                            console.log("delDoc1 err: " + res.code)
                        }
                    })
                    .catch(error => console.error(error));
            } else {
                localStorage.setItem('tokenInfo', '')
                alert("登陆过期，请登陆后再试")
                window.open('./login.html')
            }
        }
    </script>

</body>

</html>